import {
  call, put, all, takeLatest, select
} from 'redux-saga/effects'
import Taro from '@tarojs/taro'
import api from '@API'

import {
  START_PAIN_MANAGEMENT,
  GET_MY_PAIN_MANAGEMENT,
  SET_DAILY_CONTENT_VIEWED,
  GET_MANAGEMENT_TEMPLATE,
  GET_MANAGEMENT_TEMPLATES,
  GET_PAIN_MANAGEMENT_SUMMARY,
  UPDATE_PAIN_MANAGEMENT,
  GET_RECOMMEND_GOODS,
  GET_ALL_HOME_EVENTS,
  GET_EVENTS_RECOMMEND_GOODS,
  GET_EVENTS_HOME_PERSONA,
  GET_EVENTS_HOME_PAGE_SPOT,
  GET_EVENTS_HOME_PAIN_DESC,
  GET_MY_EXPIRED_PAIN_MANAGEMENT_LIST,
  GET_PAIN_MANAGEMENT_RESULT, GET_RECOMMEND_PLAN,
} from '@ACTIONS/managementPlan'
import { showToast } from '@UTILS/common'
import { getMyPainManagementData, getPainLogPatient } from '@SAGAS/dataSelect'
import { GET_LASTEST_EXPIRED_PLAN } from '@ACTIONS/dataCenter'
import { SPOT_CODE_ENUM } from '@CONSTANTS/common'
import { GET_MY_PATIENTS, SET_PAIN_LOG_PATIENT } from '@ACTIONS/patient'
import Navigate from '@NAVIGATION/navigateManager'

const startPainManagement = function* startPainManagement(action) {
  try {
    const { payload = {}, isSavePatient } = action
    yield call(api.startPainManagement, payload)
    yield put({ type: GET_MY_PAIN_MANAGEMENT.REQUEST })
    yield put({ type: START_PAIN_MANAGEMENT.SUCCESS })
    showToast('加入成功')
    isSavePatient && (setTimeout(() => { Navigate.switchTab('homePage') }, 800))
  } catch (error) {
    yield put({ type: START_PAIN_MANAGEMENT.FAILURE, error })
  }
}

const getMyPainManagement = function* getMyPainManagement() {
  try {
    const data = yield call(api.getMyPainManagement, {})
    const { PainManagementId: pId } = data || {}
    yield put({ type: GET_MY_PAIN_MANAGEMENT.SUCCESS, data })
    if (pId) {
      yield put({ type: GET_PAIN_MANAGEMENT_SUMMARY.REQUEST, payload: { pId } })
    }
  } catch (error) {
    yield put({ type: GET_MY_PAIN_MANAGEMENT.FAILURE, error })
  }
}

const getManagementTemplate = function* getManagementTemplate(action) {
  try {
    const { payload, callBack } = action
    const data = yield call(api.getManagementTemplate, payload)
    const result = yield call(api.getMyPatients, {})
    yield put({ type: GET_MY_PATIENTS.SUCCESS, result })
    const prePainLogPatient = yield select(getPainLogPatient)
    const painLogPatient = result?.find(item => item.HasPainLog) || null
    if (painLogPatient && painLogPatient.p8Id !== prePainLogPatient?.p8Id) {
      yield put({ type: SET_PAIN_LOG_PATIENT.REQUEST, result: painLogPatient })
    }
    callBack?.(data, result, painLogPatient)
    const { IntoArticle } = data
    let htmlContent
    if (IntoArticle?.FeedItemId) {
      const { FeedItem: { HtmlContent } } = yield call(api.getFeedItemDetail, { fId: IntoArticle?.FeedItemId })
      htmlContent = HtmlContent
    }
    yield put({ type: GET_MANAGEMENT_TEMPLATE.SUCCESS, data, htmlContent })
  } catch (error) {
    yield put({ type: GET_MANAGEMENT_TEMPLATE.FAILURE, error })
  }
}

const setDailyContentViewed = function* setDailyContentViewed(action) {
  try {
    const { payload = {} } = action
    yield call(api.setDailyContentViewed, payload)
    yield put({ type: UPDATE_PAIN_MANAGEMENT.REQUEST })
  } catch (error) {
    yield put({ type: SET_DAILY_CONTENT_VIEWED.FAILURE, error })
  }
}

const getManagementTemplates = function* getManagementTemplates(action) {
  try {
    const { isGuide } = action
    let serviceApi = api.getManagementTemplates
    let params = {}
    if (isGuide) {
      params = { dta: true }
      serviceApi = api.getAndSortRecommendPainManagements
    }
    const { Templates } = yield call(serviceApi, params)
    yield put({ type: GET_MANAGEMENT_TEMPLATES.SUCCESS, data: Templates })
  } catch (error) {
    yield put({ type: GET_MANAGEMENT_TEMPLATES.FAILURE, error })
  }
}

const getPainManagementSummary = function* getPainManagementSummary(action) {
  try {
    const { payload } = action
    const data = yield call(api.getPainManagementSummary, payload)
    yield put({ type: GET_PAIN_MANAGEMENT_SUMMARY.SUCCESS, data })
  } catch (error) {
    yield put({ type: GET_PAIN_MANAGEMENT_SUMMARY.FAILURE, error })
  }
}

const updateMyPainManagement = function* updateMyPainManagement() {
  const myPainManagement = yield select(getMyPainManagementData)
  const { PainManagementId: pId } = myPainManagement || {}
  if (!pId) return
  yield put({ type: GET_MY_PAIN_MANAGEMENT.REQUEST })
}

const getRecommendGoods = function* getRecommendGoods(action) {
  const { tagsStr } = action
  try {
    const { GoodsList } = yield call(api.getRecommendGoods, { take: 2, skip: 0, tIds: tagsStr, empty: true })
    yield put({ type: GET_RECOMMEND_GOODS.SUCCESS, data: GoodsList })
  } catch (error) {
    yield put({ type: GET_RECOMMEND_GOODS.FAILURE, error })
  }
}

const getRecommendGoodsEvents = function* getRecommendGoodsEvents() {
  try {
    const result = yield call(api.getEventsListBySpotCode, { code: SPOT_CODE_ENUM.RecommendGoods })
    yield put({ type: GET_EVENTS_RECOMMEND_GOODS.SUCCESS, data: result })
  } catch (error) {
    yield put({ type: GET_EVENTS_RECOMMEND_GOODS.FAILURE, error })
  }
}
const getAllHomeEvents = function* getAllHomeEvents() {
  try {
    // const result = yield call(api.getEventsListBySpotCodes, { codes: ['HomeBannerExtend', 'HomeBanner'] })
    const result = yield call(api.getEventsListBySpotCode, { code: 'HomeBannerExtend' })
    yield put({ type: GET_ALL_HOME_EVENTS.SUCCESS, data: result })
  } catch (error) {
    yield put({ type: GET_ALL_HOME_EVENTS.FAILURE, error })
  }
}
const getHomePersonaEvents = function* getHomePersonaEvents() {
  try {
    const result = yield call(api.getEventsListBySpotCode, { code: SPOT_CODE_ENUM.HomePersona })
    yield put({ type: GET_EVENTS_HOME_PERSONA.SUCCESS, data: result })
  } catch (error) {
    yield put({ type: GET_EVENTS_HOME_PERSONA.FAILURE, error })
  }
}
const getHomePageSpotEvents = function* getHomePageSpotEvents() {
  try {
    const result = yield call(api.getEventsListBySpotCode, { code: SPOT_CODE_ENUM.HomePageSpot })
    yield put({ type: GET_EVENTS_HOME_PAGE_SPOT.SUCCESS, data: result })
  } catch (error) {
    yield put({ type: GET_EVENTS_HOME_PAGE_SPOT.FAILURE, error })
  }
}

const getHomePainDescEvents = function* getHomePainDescEvents() {
  try {
    const result = yield call(api.getEventsListBySpotCode, { code: SPOT_CODE_ENUM.PainManagementDescription })
    yield put({ type: GET_EVENTS_HOME_PAIN_DESC.SUCCESS, data: result })
  } catch (error) {
    yield put({ type: GET_EVENTS_HOME_PAIN_DESC.FAILURE, error })
  }
}

const getMyExpiredPainManagementList = function* getMyExpiredPainManagementList() {
  try {
    const { PainManagementList } = yield call(api.getMyExpiredPainManagementList)
    yield put({ type: GET_MY_EXPIRED_PAIN_MANAGEMENT_LIST.SUCCESS, data: PainManagementList })
  } catch (error) {
    yield put({ type: GET_MY_EXPIRED_PAIN_MANAGEMENT_LIST.FAILURE, error })
  }
}
const getPainManagementResult = function* getPainManagementResult(action) {
  try {
    const { pId } = action
    const result = yield call(api.getPainManagementResult, { pId })
    yield put({ type: GET_PAIN_MANAGEMENT_RESULT.SUCCESS, result, pId })
    yield put({ type: GET_LASTEST_EXPIRED_PLAN.REQUEST })
  } catch (error) {
    yield put({ type: GET_PAIN_MANAGEMENT_RESULT.FAILURE, error })
  }
}

const getMyRecommendPainManagements = function* getMyRecommendPainManagements() {
  try {
    const result = yield call(api.getMyRecommendPainManagements, {})
    yield put({ type: GET_RECOMMEND_PLAN.SUCCESS, data: result?.Templates || [] })
  } catch (error) {
    yield put({ type: GET_RECOMMEND_PLAN.FAILURE, error })
  }
}
export default function* rootSaga() {
  yield all([
    takeLatest(START_PAIN_MANAGEMENT.REQUEST, startPainManagement),
    takeLatest(GET_MY_PAIN_MANAGEMENT.REQUEST, getMyPainManagement),
    takeLatest(GET_MANAGEMENT_TEMPLATE.REQUEST, getManagementTemplate),
    takeLatest(SET_DAILY_CONTENT_VIEWED.REQUEST, setDailyContentViewed),
    takeLatest(GET_MANAGEMENT_TEMPLATES.REQUEST, getManagementTemplates),
    takeLatest(GET_PAIN_MANAGEMENT_SUMMARY.REQUEST, getPainManagementSummary),
    takeLatest(UPDATE_PAIN_MANAGEMENT.REQUEST, updateMyPainManagement),
    takeLatest(GET_RECOMMEND_GOODS.REQUEST, getRecommendGoods),
    takeLatest(GET_EVENTS_RECOMMEND_GOODS.REQUEST, getRecommendGoodsEvents),
    takeLatest(GET_ALL_HOME_EVENTS.REQUEST, getAllHomeEvents),
    takeLatest(GET_EVENTS_HOME_PERSONA.REQUEST, getHomePersonaEvents),
    takeLatest(GET_EVENTS_HOME_PAGE_SPOT.REQUEST, getHomePageSpotEvents),
    takeLatest(GET_EVENTS_HOME_PAIN_DESC.REQUEST, getHomePainDescEvents),
    takeLatest(GET_MY_EXPIRED_PAIN_MANAGEMENT_LIST.REQUEST, getMyExpiredPainManagementList),
    takeLatest(GET_PAIN_MANAGEMENT_RESULT.REQUEST, getPainManagementResult),
    takeLatest(GET_RECOMMEND_PLAN.REQUEST, getMyRecommendPainManagements),
  ])
}
